package com.xiaohao.springbootadmintemplate.config.securitycontext;

import com.xiaohao.springbootadmintemplate.bean.User;
import com.xiaohao.springbootadmintemplate.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    //调用Dao层加载用户
    private UserDao userDao;

    @Override
    //根据用户名加载用户
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = userDao.findByUsername(name);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", name));
        } else {
            return new SecurityContextUserDetails(user.getUsername(), user.getPassword(), user.getRoles());
        }
    }
}
